package com.ysstech.activiti.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

import com.ysstech.activiti.model.DeploymentEntity;
import com.ysstech.activiti.model.ProcessDefinitionEntity;
import com.ysstech.activiti.service.ActivitiRepositoryService;
import com.ysstech.common.entity.PageBean;
import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.util.fileutil.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service
public class ActivitiRepositoryServiceImpl implements ActivitiRepositoryService {

    @Autowired
    private RepositoryService repositoryService;

    /**
     * 部署流程定义
     */
    @Override
    public void repositoryFlow(MultipartFile file, String filename) throws Exception {
        File newfile = null;
        try {
            if (null == file) {
                throw new BusinessException("获取文件数据失败，请稍后重试！");
            }
            newfile = FileUtil.MultipartFileToFile(file);
            if (null == newfile) {
                throw new BusinessException("获取文件数据失败，请稍后重试！");
            }
            //2：将File类型的文件转化成ZipInputStream流
            ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(newfile));
            repositoryService.createDeployment()//创建部署对象
                    .name(filename)//添加部署名称
                    .addZipInputStream(zipInputStream)////指定zip格式的文件完成部署
                    .deploy();//完成部署
            //repositoryService.createDeployment().addClasspathResource("role.bpmn").deploy();
        } catch (BusinessException ex) {
            throw new BusinessException(ex.getMessage());
        } finally {
            FileUtil.delteTempFile(newfile);
        }
    }

    /**
     * 查询部署对象信息，对应表（act_re_deployment）
     */
    @Override
    public Map<String, Object> queryDeployment(PageBean page) throws Exception {
        int pageNumber = Integer.parseInt(String.valueOf(page.getPageNum()));
        int pageSize = Integer.parseInt(String.valueOf(page.getPageSize()));
        List<Deployment> list = repositoryService.createDeploymentQuery()//创建部署对象查询
                .orderByDeploymenTime().asc()
                .listPage((pageNumber - 1) * pageSize, pageSize);
        Long count = repositoryService.createProcessDefinitionQuery().count();
        List<DeploymentEntity> deploymentEntityList = new ArrayList<>();
        for (Deployment deployment : list) {
            DeploymentEntity deploymentEntity = new DeploymentEntity();
            deploymentEntity.setDeploymentTime(deployment.getDeploymentTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime());
            deploymentEntity.setId(deployment.getId());
            deploymentEntity.setName(deployment.getName());
            //查询流程定义的信息
            ProcessDefinitionEntity processDefinitionEntity = this.findProcessDefinitionList(deployment.getId());
            deploymentEntity.setProcessDefinitionEntity(processDefinitionEntity);
            deploymentEntityList.add(deploymentEntity);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", deploymentEntityList);
        map.put("total", count);
        return map;
    }

    /**
     * 查询流程定义的信息
     *
     * @param deploymentId
     * @return
     * @throws Exception
     */
    public ProcessDefinitionEntity findProcessDefinitionList(String deploymentId) throws Exception {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()//创建流程定义查询
                .deploymentId(deploymentId).singleResult();
        ProcessDefinitionEntity processDefinitionEntity = new ProcessDefinitionEntity();
        processDefinitionEntity.setCategory(processDefinition.getCategory());
        processDefinitionEntity.setDeploymentId(processDefinition.getDeploymentId());
        processDefinitionEntity.setDiagramResourceName(processDefinition.getDiagramResourceName());
        processDefinitionEntity.setVersion(processDefinition.getVersion());
        processDefinitionEntity.setId(processDefinition.getId());
        processDefinitionEntity.setKey(processDefinition.getKey());
        processDefinitionEntity.setName(processDefinition.getName());
        processDefinitionEntity.setResourceName(processDefinition.getResourceName());
        processDefinitionEntity.setTenantId(processDefinition.getTenantId());
        return processDefinitionEntity;
    }

    /**
     * 使用部署对象ID，删除流程定义
     */
    @Override
    public void deleteProcess(String deploymentId) throws Exception {
        repositoryService.deleteDeployment(deploymentId, true);
    }


    /**
     * 使用部署对象ID和资源图片名称，获取图片的输入流
     */
    @Override
    public InputStream imageInputStream(String deploymentId, String imageName) throws Exception {
        return repositoryService.getResourceAsStream(deploymentId, imageName);
    }

}
